﻿using SD.Infrastructure.Repository.EntityFrameworkCore;
using SD.Infrastructure.RepositoryBase;
using SlamDunk.MES.Domain.Entities.StockContext;
using SlamDunk.MES.Domain.IRepositories.Interfaces.StockContext;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace SlamDunk.MES.Repository.Implements.StockContext
{
    /// <summary>
    /// 物料条码仓储实现
    /// </summary>
    public class MaterialBarcodeRepository : EFAggRootRepositoryProvider<MaterialBarcode>, IMaterialBarcodeRepository
    {
        #region # 分页获取物料条码列表 —— ICollection<MaterialBarcode> FindByPage(Guid? materialId...
        /// <summary>
        /// 分页获取物料条码列表
        /// </summary>
        /// <param name="materialId">物料定义Id</param>
        /// <param name="materialLotId">物料批次Id</param>
        /// <param name="facilityIds">工厂模型Id集</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页容量</param>
        /// <param name="rowCount">总记录数</param>
        /// <param name="pageCount">总页数</param>
        /// <returns>物料条码列表</returns>
        public ICollection<MaterialBarcode> FindByPage(Guid? materialId, Guid? materialLotId, IList<Guid> facilityIds, int pageIndex, int pageSize, out int rowCount, out int pageCount)
        {
            Expression<Func<MaterialBarcode, bool>> condition =
                x =>
                    (materialId == null || x.MaterialId == materialId) &&
                    (materialLotId == null || x.MaterialLotId == materialLotId);

            IQueryable<MaterialBarcode> materialBarcodes = base.Find(condition);
            if (facilityIds != null && facilityIds.Any())
            {
                materialBarcodes = materialBarcodes.Where(x => x.FacilityId.HasValue && facilityIds.Contains(x.FacilityId.Value));
            }

            IOrderedQueryable<MaterialBarcode> orderedResult = materialBarcodes.OrderByDescending(x => x.AddedTime);
            IQueryable<MaterialBarcode> pagedResult = orderedResult.ToPage(pageIndex, pageSize, out rowCount, out pageCount);

            return pagedResult.ToList();
        }
        #endregion
    }
}
